using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace ZuDoKu.Controls
{
    public class RadialMenuItem : Button, IRadialItem
    {
        public double Radius { get; set; }

        public RadialMenuItem(Texture2D texture) 
            : base(texture) 
        {
            Radius = 50;
            this.Pressed += new EventHandler(RadialMenuItem_Pressed);
        }

        void RadialMenuItem_Pressed(object sender, EventArgs e)
        {
            foreach (Control sub in Controls)
                sub.Visible = true;
        }

        public void Add(RadialMenuItem subItem)
        {
            subItem.Visible = false;
            Controls.Add(subItem);
            (this as IRadialItem).PerformLayout();
        }

        #region IRadialItem Members

        double IRadialItem.Range { get; set; }
        double IRadialItem.Theta { get; set; }

        void IRadialItem.PerformLayout()
        {
            int count = 0;
            foreach (Control c in Controls)
            {
                if (c is RadialMenuItem)
                    count++;
            }

            double range = (this as IRadialItem).Range;
            double theta = range / count;
            double start = (this as IRadialItem).Theta - (range / 2d);

            int n = 0;
            foreach(Control control in Controls)
            {
                RadialMenuItem item = control as RadialMenuItem;
                if (item != null)
                {
                    double itemTheta = start + (theta * n);

                    int y = (int)(Radius * Math.Sin(itemTheta)) * -1;
                    int x = (int)(Radius * Math.Cos(itemTheta));

                    item.X = x - (item.Width / 2);
                    item.Y = y - (item.Height / 2);

                    (item as IRadialItem).Theta = itemTheta;
                    (item as IRadialItem).PerformLayout();
                    n++;
                }
            }
        }

        public override void Draw(SpriteBatch batch, GameTime gameTime, int offsetX, int offsetY, byte transparency)
        {
            base.Draw(batch, gameTime, offsetX, offsetY, transparency);
        }

        #endregion
    }
}